<main>
    <?php
    if (!isset($_SESSION['chapterPanel']) && isset($_SESSION['subjectPanel'])) {
        header("location: ../logic/goBack.php");
    }
    $chapterID = $_SESSION['chapterPanel'];
    $subjectID = $_SESSION['subjectPanel'];

    $sql_query = "SELECT chapterID, subjectID, startDate, endDate, revisionAllowed, numQuestions FROM tests WHERE chapterID = $chapterID AND subjectID = '$subjectID'";
    $result = mysqli_query($db, $sql_query);
    $row = mysqli_fetch_assoc($result);
    if ($row) {
        $startDate = $row['startDate'];
        $endDate = $row['endDate'];
		date_default_timezone_set('Europe/Madrid');
        if (new DateTime() > new DateTime($row['endDate'])) {
            echo "<center>Exam time ended <b>(from $startDate to $endDate)</b>, now you can see the results";
            showResults($db);
            echo '<a href="/teacher/logic/resetExam.php">Reset this exam</a>';
            echo "</center>";
        } else if (new DateTime() > new DateTime($row['startDate'])) {
            echo "<center>Exam is taking place right now <b>(from $startDate to $endDate)</b>, you will see the results after finishing";
            echo "</center>";
        } else {
            echo '<center>';
            echo "Exam was set between $startDate and $endDate with revision ";
            if ($row['revisionAllowed'] == 1) {
                echo "<b>allowed</b> ";
            } else {
                echo "<b>not allowed</b> ";
            }
            $num = $row['numQuestions'];
            echo "with $num questions";
            showError();
            echo "</center>";
            showExamForm();
        }
    } else {
        echo '<center><h1>Exam date was not set</h1>';
        showError();
        echo "</center>";
        showExamForm();
    }
    unset($_SESSION['error']);






    function showResults($db)
    {
        $chapter = $_SESSION['chapterPanel'];
        $subject = $_SESSION['subjectPanel'];
        $query_result = "SELECT * FROM (SELECT * FROM results WHERE chapterID = '$chapter') AS results RIGHT JOIN students_subjects ON results.studentUser = students_subjects.studentID WHERE students_subjects.subjectID = (SELECT subjects.subjectID from subjects where subjects.subjectName='$subject')";
        $result_first = mysqli_query($db, $query_result);
        $result_second = mysqli_query($db, $query_result);
        echo '<table border="1px" id="users">
        <thead>
            <tr>
                <th>Student</th>
                <th>Grade</th>
            </tr>
        </thead>
        <tbody>';


        while ($row = mysqli_fetch_assoc($result_first)) {
            if ($chapter == $row['chapterID'] || !isset($row['chapterID'])) {
                if ($row['score'] == 0) {
                    $grade = 0.0;
                } else {
                    $grade = round($row['score'] / $row['maxPoints'] * 10, 1);
                }

                echo '<tr>
                        <td>' . $row['studentID'] . '</td>
                        <td>' . $grade . '</td>
                    </tr>';
            }
        }
        echo '</tbody>
    </table>';



        echo '<table border="1px" id="users">
        <thead>
            <tr>
                <th>Numero de suspensos</th>
                <th>Numero de aprobados</th>
                <th>Numero de notables</th>
                <th>Numero de sobresalientes</th>
                <th>Nota media de la clase</th>
            </tr>
        </thead>
        <tbody>';

        $suspensos = 0;
        $aprobados = 0;
        $notables = 0;
        $sobresalientes = 0;
        $students = 0;
        $sumGrade = 0;
        while ($row = mysqli_fetch_assoc($result_second)) {
            if (isset($row['score'])) {
                $grade = round($row['score'] / $row['maxPoints'] * 10, 1);
                if ($grade < 5) {
                    $suspensos = $suspensos + 1;
                } else if ($grade < 7) {
                    $aprobados = $aprobados + 1;
                } else if ($grade < 9) {
                    $notables = $notables + 1;
                } else {
                    $sobresalientes = $sobresalientes + 1;
                }
                $students = $students + 1;
                $sumGrade = $sumGrade + $grade;
            } else {
                $suspensos = $suspensos + 1;
                $students = $students + 1;
            }
        }

        if ($sumGrade == 0) {
            $notaMedia = 0;
        } else {
            $notaMedia = round($sumGrade / $students, 1);
        }

        echo '<tr>
                    <td>' . $suspensos . '</td>
                    <td>' . $aprobados . '</td>
                    <td>' . $notables . '</td>
                    <td>' . $sobresalientes . '</td>
                    <td>' . $notaMedia . '</td>
                </tr>';
        echo '</tbody>
    </table>';
    }


    function showExamForm()
    {
        echo '<div class="form">
        <form action="logic/examLogic.php" method="POST">

            <label for="startDate">Start time</label><br>
            <input type="date" id="startDate" name="startDate" required>
            <input type="time" id="startTime" name="startTime" required><br><br>

            <label for="endDate">End time</label><br>
            <input type="date" id="endDate" name="endDate" required>
            <input type="time" id="endTime" name="endTime" required><br><br>

            <label for="revision">Revision allowed</label><br>
            <input type="checkbox" id="revision" name="revision"><br><br>

            <label for="questionNumber">Amount of questions (0-100)</label><br>
            <input type="number" id="questionNumber" name="questionNumber" step="1" min="0" max="100" required>

            <input type="submit" value="Set exams">
        </form>
    </div>';
    }


    function showError()
    {
        if (isset($_SESSION['error'])) {
            if ($_SESSION['error'] == 1) {
                echo '<p style="color:red"> You can not set exam end date before starting date</p>';
            } else {
                echo '<p style="color:red"> You can not set exam start date in the past</p>';
            }
        }
    }
    ?>


</main>
